package com.online.teaching.interceptor;

import com.online.teaching.config.UrlFilter;
import org.apache.tomcat.util.http.MimeHeaders;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;

/**
 * @ClassName : LoginInterceptor  //类名
 * @Description :   //描述
 * @Author : YG  //作者
 * @Date: 2020-11-22 15:43  //时间
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    private static final String AUTHORIZE_TOKEN = "Authorization";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截了");
        //3.判断 是否为登录的URL 如果是 放行
        if(UrlFilter.hasAutorize(request.getRequestURI())){
            return true;
        }
        //4.判断 是否为登录的URL 如果不是      权限校验

        //4.1 从头header中获取令牌数据
        String token = request.getHeader(AUTHORIZE_TOKEN);

        if(StringUtils.isEmpty(token)){
            //4.2 从cookie中中获取令牌数据
            Cookie[] cookies = request.getCookies();
            if(cookies==null){
                outPutErrorResult(response);
                return false;
            }
            for (int i = 0; i < cookies.length; i++) {
                if(cookies[i].getName().equals(AUTHORIZE_TOKEN)){
                    token=cookies[i].getName();
                }
            }
        }

        if(StringUtils.isEmpty(token)){
            //返回401状态码
            response.setStatus(401);
            return false;
        }
        request.setAttribute(AUTHORIZE_TOKEN,"Bearer "+ token);
        HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper((HttpServletRequest) request) {
            /**
             * 当调用request.getHeader("token")时，则获取请求参数中token值并当做Header的值返回
             * @param name
             * @return
             */
            @Override
            public String getHeader(String name) {
                // 先从原本的Request中获取头，如果为空且名字为token，则从参数中查找并返回
                String superHeader = super.getHeader(name);
                if(AUTHORIZE_TOKEN.equals(name) && StringUtils.isEmpty(superHeader)){
                    String token = request.getParameter(AUTHORIZE_TOKEN);
                    if (!StringUtils.isEmpty(token)) {
                        return token ;
                    }
                }
                return superHeader;
            }
        };
        //添加头信息 传递给 各个微服务()
        System.out.println(request.getHeader(AUTHORIZE_TOKEN));
        return true;
    }


    public void outPutErrorResult(HttpServletResponse response) {
        ServletOutputStream output = null;
        try {
            output = response.getOutputStream();
            output.write(("{\"flag\":\"true\",\"code\":\"20001\",\"msg\":\"请登录账号@！\"}").getBytes());
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != output) {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
